package com.nanyiba.qrcode.websocket;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Map;

/**
 * @Author 熊腾强
 * @Date 2021/8/1 2:35 下午
 * @Description 初始化websocket配置
 */
@Component
public class WebSockHandshakeHandler extends DefaultHandshakeHandler {

    /**
     * 将url修带的token参数值作为websocket session的唯一标识
     *
     * 在客户端与服务端握手的时候触发
     * ps：将请求中的参数塞到Principal中，可以理解成塞到websocket的session中，后续可通过Principal principal = session.getPrincipal()获取到
     */
    @Override
    protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletServerHttpRequest = (ServletServerHttpRequest) request;
            HttpServletRequest httpRequest = servletServerHttpRequest.getServletRequest();
            final String token = httpRequest.getParameter("token");
            if (StringUtils.isEmpty(token)) {
                return null;
            }
            return new Principal() {
                @Override
                public String getName() {
                    return token;
                }
            };
        }
        return null;
    }
}
